package com.scenic.userservice.controller;

import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.Collect;
import com.scenic.common.bean.RespBean;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.CollectService;
import com.scenic.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;
    //添加 -- 收藏
    @PostMapping("/{goodsId}")
    public RespBean insert(@PathVariable("goodsId") Long goodsId, @RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        Collect collect = new Collect(null, goodsId, userId, null, null);
        if (collectService.insert(collect)) {
            return RespBean.ok("收藏成功");
        }
        return RespBean.error("收藏失败");
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws ScenicSpotException {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        if (!collectService.delete(id, userId)) {
            return RespBean.ok("取消收藏失败");
        }

        return RespBean.ok("取消收藏成功");
    }
    @GetMapping("/{goodsId}")
    //根据商品id和用户id查询收藏
    public RespBean selectByGoodIdAndUserId(@PathVariable("goodsId") Long goodsId, @RequestHeader("token") String token) {
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");
        Collect collect = collectService.selectByGoodIdAndUserId(goodsId, userId);

        return RespBean.ok("",collect);
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (Integer pageNum, Integer pageSize,@RequestHeader("token") String token ) throws ScenicSpotException {
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");


        PageInfo<Collect> pageInfo = collectService.selectByPage(pageNum, pageSize, userId);

        return RespBean.ok("",pageInfo);
    }
}
